<script lang="ts" setup>
import { cloneDeep } from 'lodash-es';
import { onMounted, reactive, ref, nextTick } from 'vue';
import { message } from 'ant-design-vue';
import { getStyRoleApi, getSysRoleListEnabledApi, getSysRoleIdApi, deleteSysRoleIdApi, putSysRoleIdApi } from '@/common/apis/role'
import backgNewRole from '@/common/components/backg-role/backg-new-role.vue'
import backgAssignPower from '@/common/components/backg-role/backg-assign-power.vue';
import type { UnwrapRef } from 'vue';
import type { DataItem } from '@/common/types/role-type'
import type { SwitchPagination } from '@/common/types/information-type'

// 储存的数据
const styRoleData = ref<DataItem>();

const checked = ref(true)
// 新增-角色弹框
const childModalRef = ref()
// 分配权限-弹框
const assignPowerModal = ref();
// 储存角色详情数据
const roleDetail = ref();  // 存储角色详情数据


const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});


// 分页配置
const pagination = reactive({
  page: 1,
  pagesize: 5,
  pageSize: 5, // 每页条数
  total: 0, // 总数据条数
});

const columns = [
  {
    title: '序号',
    dataIndex: 'SerialNumber',
    width: '5%',
  },
  {
    title: '角色',
    dataIndex: 'name',
    width: '15%',
  },
  {
    title: '启用',
    dataIndex: 'state',
    width: '15%',
  },
  {
    title: '描述',
    dataIndex: 'description',
    width: '40%',
  },
  {
    title: '操作',
    dataIndex: 'operation',
  },
];

// 获取角色列表
const getStyRoleData = async () => {
  const res = await getStyRoleApi(pagination)
  // 将数据存储到 styRoleData 中
  styRoleData.value = res.data.data.rows
  pagination.total = res.data.data.total
}

// 点击分页获取数据
const handleTableChange = async (page: SwitchPagination) => {
  pagination.page = page.current; // 更新当前页码
  pagination.pagesize = page.pageSize; // 更新当前条数
  await getStyRoleData()
}


// 获取角色详情
const getSysRoleIdData = async (id: string) => {
  const res = await getSysRoleIdApi(id)
  roleDetail.value = res.data.data
}

// 获取已启动的角色列表
const getSysRoleListEnabledData = async () => {
  await getSysRoleListEnabledApi()
}

// 新增角色弹框
const onClickNewRole = () => {
  childModalRef.value.showModal()
}


// 点击分配权限
const assignPermission = async (id: string) => {
  // 获取点击的id
  getSysRoleIdData(id)

  // 确保子组件的 ref 已绑定
  await nextTick();

  // 调用子组件的 showModal 方法
  assignPowerModal.value.showModal();
};

// 点击编辑
const edit = async (id: string) => {
  // 获取点击的id
  getSysRoleIdData(id);

  // 进入编辑模式
  editableData[id] = cloneDeep(styRoleData.value?.find((item: DataItem) => id === item.id));

  checked.value = editableData[id].state === 1;
};

// 点击删除
const deleteItem = async (id: string) => {
  // 获取点击的id
  getSysRoleIdData(id)
  // 删除角色
  const res = await deleteSysRoleIdApi(id)

  if (res.data.code === 10000) {
    // 刷新
    getStyRoleData()
    message.success('删除成功');
  } else {
    message.error(res.data.message)
  }

};

// 保存
const save = async (id: string) => {
  console.log(id, checked.value, '保存的数据')

  const item = styRoleData.value?.find((item: DataItem) => id === item.id);

  if (item && editableData[id]) {
    // 根据 checked.value 更新 state
    editableData[id].state = checked.value ? 1 : 0;

    // 调用接口保存数据
    const res = await putSysRoleIdApi(editableData[id]);
    if (res.data.code === 10000) {
      // 退出编辑模式
      delete editableData[id];
      // 刷新
      getStyRoleData()
      message.success('保存成功');
    } else {
      message.error(res.data.message)
    }
  }
};

// 取消
const cancel = (id: string) => {
  delete editableData[id];
};


onMounted(() => {
  getStyRoleData();
  getSysRoleListEnabledData()
});
</script>

<template>
  <!-- 新增角色 -->
  <a-button type="primary" @click="onClickNewRole">新增</a-button>
  <backgNewRole ref="childModalRef" :getStyRoleData="getStyRoleData"></backgNewRole>
  <a-table :columns="columns" :pagination="pagination" @change="handleTableChange" :data-source="styRoleData" bordered>
    <template #bodyCell="{ column, text, record }">
      <!-- 序号 -->
      <template v-if="column.dataIndex === 'SerialNumber'">
        <span>{{ record.id }}</span>
      </template>
      <!-- 判断 编辑模式 后传值 -->
      <template v-if="column.dataIndex === 'state'">
        <div>
          <!-- 编辑模式下显示开关 -->
          <a-switch v-if="editableData[record.id]" v-model:checked="checked" />
          <!-- 非编辑模式下显示 Enable 列的值 -->
          <template v-else>
            {{ text === 1 ? '已启动' : '未启动' }}
          </template>
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'name' || column.dataIndex === 'description'">
        <div>
          <a-input v-if="editableData[record.id]"
            v-model:value="editableData[record.id][column.dataIndex as keyof DataItem]" style="margin: -5px 0" />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'operation'">
        <div class="editable-row-operations">
          <!-- 取消-保存 -->
          <span v-if="editableData[record.id]">

            <a-typography-link @click="save(record.id)">保存</a-typography-link>
            <!-- 取消二次确认 -->
            <a-popconfirm title="确定取消么" @confirm="cancel(record.id)">
              <a>取消</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="assignPermission(record.id)">分配权限</a>
            <a @click="edit(record.id)">编辑</a>
            <a-popconfirm title="你确定删除么?" @confirm="deleteItem(record.id)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </div>
      </template>
    </template>
  </a-table>

  <!-- 分配角色 -->
  <backgAssignPower v-show="roleDetail?.permIds" :roleDetail="roleDetail" ref="assignPowerModal" />

</template>

<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>